package com.jic.manager.controller.manage.sys;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.manager.entity.Merchant;
import com.jic.manager.entity.SysRole;
import com.jic.manager.entity.SysUser;
import com.jic.manager.request.*;
import com.jic.manager.response.SysUserResponse;
import com.jic.manager.response.UccUserResponse;
import com.jic.manager.service.MerchantService;
import com.jic.manager.service.SysRoleService;
import com.jic.manager.service.SysUserService;
import com.jic.manager.utils.MD5Utils;
import com.jic.util.BaseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 机构控制器
 * @autho wwb
 */
@SuppressWarnings("all")
@Slf4j
@Api(tags = "系统用户Controller")
@RestController
@RequestMapping("sysUser")
public class SysUserController{

    @Autowired
    private RedisClientTemplate redisClientTemplate;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private MerchantService merchantService;

    @PostMapping(value = "/sysUserQueryPage")
    public RestResult<PageResult<SysUserResponse>> sysUserQueryPage(@RequestBody SysUserRequest sysUserRequest) {
        try{
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserRequest,sysUser);
            if (sysUserRequest.getStart() != null && sysUserRequest.getStart() != 0 && sysUserRequest.getLimit() != null){
                //分页
                PageResult<SysUser> sysUserPageResult = sysUserService.queryPage(sysUser, new Page() {{
                    setStart(sysUserRequest.getStart());
                    setLimit(sysUserRequest.getLimit());
                }});
                List<SysUserResponse> sysUserResponseList = new ArrayList<>();
                List<SysUser> sysUserList = sysUserPageResult.getRows();
                sysUserList.forEach(sysUserVo -> {
                    SysUserResponse sysUserResponse = new SysUserResponse();
                    BeanUtils.copyProperties(sysUserVo,sysUserResponse);
                    if(StringUtils.isNotEmpty(sysUserResponse.getFlag())){
                        sysUserResponse.setPassword(null);
                    }
                    SysRole sysRole = sysRoleService.queryByPrimaryKey(sysUserResponse.getRoleid());
                    if (sysRole != null){
                        sysUserResponse.setRoleName(sysRole.getRoleName());
                    }
                    sysUserResponseList.add(sysUserResponse);
                });
                return new RestResult<PageResult<SysUserResponse>>(){{
                   setCode("0000");
                   setData(new PageResult<SysUserResponse>(){{
                       setRows(sysUserResponseList);
                       setTotal(sysUserPageResult.getTotal());
                   }});
                }};
            }else{
                sysUser.setCreator(null);
                List<SysUser> sysUsers = sysUserService.query(sysUser);
                List<SysUserResponse> sysUserResponseList = new ArrayList<>();
                sysUsers.forEach(sysUserVo1 -> {
                    if(StringUtils.isNotEmpty(sysUserVo1.getFlag())){
                        sysUserVo1.setPassword(null);
                    }
                    SysUserResponse sysUserResponse = new SysUserResponse();
                    BeanUtils.copyProperties(sysUserVo1,sysUserResponse);
                    //查询角色名称
                    SysRole sysRole = sysRoleService.queryByPrimaryKey(sysUserVo1.getRoleid());
                    if (sysRole != null){
                        sysUserResponse.setRoleName(sysRole.getRoleName());
                        sysUserResponseList.add(sysUserResponse);
                    }
                    //查询所属商家
                    if (sysUserVo1.getDeptId() != null && sysUserVo1.getDeptId() != 0){
                        Merchant merchant = merchantService.queryByPrimaryKey(sysUserVo1.getDeptId());
                        sysUserResponse.setMMerchantList(new ArrayList<Object>(){{
                            add(merchant);
                        }});
                    }
                    sysUserResponseList.add(sysUserResponse);
                });
                return new RestResult<PageResult<SysUserResponse>>(){{
                    setCode("0000");
                    setData(new PageResult<SysUserResponse>(){{
                        setRows(sysUserResponseList);
                    }});
                }};

            }
        }catch (Exception e){
            e.printStackTrace();
            return new RestResult<PageResult<SysUserResponse>>(){{
                setCode("9999");
                setMsg(e.getLocalizedMessage());
            }};
        }
    }

    @PostMapping("editSysUser")
    public RestResult<String> editSysUser(@RequestBody SysUserRequest sysUserRequest){
        return sysUserService.editSysUser(sysUserRequest);
    }

    @PostMapping("deleteSysUser")
    public RestResult<String> deleteSysUser(@RequestBody SysUserRequest sysUserRequest){
        return sysUserService.deleteSysUser(sysUserRequest);
    }

    @PostMapping("getSysUserInfoByToken")
    public RestResult<SysUserResponse> getSysUserInfoByToken(@RequestBody SysUserRequest sysUserRequest){
        try {
            if (StringUtils.isEmpty(sysUserRequest.getToken())) {
                throw new Exception("必传参数为空 token");
            }
            String userStr = redisClientTemplate.get(sysUserRequest.getToken());
            if (StringUtils.isEmpty(userStr)){
                return RestResult.error("4000","登录失效");
            }
            SysUser sysUser = JSONArray.parseObject(userStr, SysUser.class);
            SysUser sysUserVo = sysUserService.queryByPrimaryKey(sysUser.getId());
            if (sysUserVo == null) {
                throw new Exception("当前用户不存在 userId = "+sysUser.getId());
            }
            if(sysUserVo.getDeleteFlag().equals(1)) {
                throw new Exception("当前用户已被删除 userId = "+sysUserVo.getId());
            }
            if (sysUserVo.getStatus() == 0){
                throw new Exception("当前用户已冻结 userId="+sysUserVo.getId());
            }else if(sysUserVo.getStatus() == 2){
                throw new Exception("当前用户未审核 userId="+sysUserVo.getId());
            }
            SysUserResponse sysUserResponse = new SysUserResponse();
            BeanUtils.copyProperties(sysUserVo,sysUserResponse);
            return RestResult.success(sysUserResponse);
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @PostMapping("editSysUserPassWord")
    public RestResult<String> editSysUserPassWord(@RequestBody SysUserRequest sysUserRequest){
        try {
            String token = sysUserRequest.getToken();
//            String userStr = redisClientTemplate.get(token);
//            if(StringUtils.isEmpty(token) || StringUtils.isEmpty(userStr)){
//                return RestResult.error("4000","登录失效");
//            }
//            SysUser sysUser = JSONArray.parseObject(userStr, SysUser.class);
            SysUser sysUserVo = sysUserService.queryByPrimaryKey(1L);
            if (sysUserVo == null){
                return RestResult.error("9999","当前用户不存在");
            }
            if (sysUserVo.getDeleteFlag().equals(1)){
                return RestResult.error("9999","当前账号已冻结");
            }
//        sysUserVo.setPassword(new String(EncryptionUtils.decipher(sysUserVo.getPassword(),sysUserVo.getFlag())));
//            String oldpassword = sysUserRequest.getOldpassword();
//            String newpassword = sysUserRequest.getNewpassword();
//            String confimpassword = sysUserRequest.getConfimpassword();
//            if (StringUtils.isEmpty(oldpassword) || StringUtils.isEmpty(newpassword) || StringUtils.isEmpty(confimpassword)){
//                return RestResult.error("9999","必传参数为空");
//            }
//            if (!MD5Utils.verify(oldpassword,sysUserVo.getFlag(),sysUserVo.getPassword())){
//                return RestResult.error("9999","原密码错误!");
//            }
//            if (!newpassword.equals(confimpassword)){
//                return RestResult.error("9999","确认密码与新密码不一致");
//            }
            //修改密码
            sysUserService.update(new SysUser(){{
                setId(sysUserVo.getId());
                setPassword(MD5Utils.md5("123123",sysUserVo.getFlag()));
            }});
            //删除登陆token
            redisClientTemplate.del(token);
            return RestResult.success("密码修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }


    @PostMapping(value = "batchReview")
    public RestResult<String> batchReview(@RequestBody SysUserRequest sysUserRequest){
        try {
            Integer status = sysUserRequest.getStatus();
            String ids = sysUserRequest.getIds();
            if (StringUtils.isEmpty(ids)) {
                throw new Exception("审核条数不能为0");
            }
            String[] idsStr = ids.split(",");
            for (int x = 0; x < idsStr.length; x++) {
                String id = idsStr[x];
                sysUserService.update(new SysUser(){{
                    setId(Long.valueOf(id));
                    setStatus(status);
                }});
            }
            return RestResult.success("审核成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }


    /**
     * 根据工号 查询用户列表
     */
    @ApiOperation("根据工号姓名查询UCC用户列表")
    @PostMapping("/getUccUserListByEmployinfo")
    public RestResult<List<UccUserResponse>> getUccUserListByEmployinfo(@RequestBody UccUserRequest uccUserRequest){
        return sysUserService.getUccUserListByEmployinfo(uccUserRequest);
    }


    /**
     * 保存UCC用户权限和信息
     */
    @ApiOperation("保存用户权限和信息")
    @PostMapping("/saveUserInfoAuthor")
    public RestResult<Boolean> saveUserInfoAuthor(@RequestBody UserAuthorRequest uccUserAuthorRequest){
        try{
            return sysUserService.saveUserInfoAuthor(uccUserAuthorRequest);
        }catch (Exception e){
            log.error("新增用户失败====>>>>{}"+e.getMessage());
            return RestResult.error("9999","服务器异常...");
        }
    }


    /**
     * 保存UCC用户权限和信息
     */
    @ApiOperation("编辑用户权限和信息")
    @PostMapping("/updateUserInfoAuthor")
    public RestResult<Boolean> updateUserInfoAuthor(@RequestBody UserAuthorRequest uccUserAuthorRequest){
        try{
            return sysUserService.updateUserInfoAuthor(uccUserAuthorRequest);
        }catch (Exception e){
            log.error("新增用户失败====>>>>{}"+e.getMessage());
            return RestResult.error("9999","服务器异常...");
        }
    }

    /**
     * 保存UCC用户权限和信息
     */
    @ApiOperation("根据架构Id查询账号列表")
    @PostMapping("/querySysUserListByDeptId")
    public RestResult<PageResult<SysUser>> querySysUserListByDeptId(@RequestBody UccUserRequest uccUserRequest){
        SysUser sysUser = new SysUser();
        if(uccUserRequest.getQueryDeptId() == null || uccUserRequest.getQueryDeptId() == 0){
            log.error("deptId 为空");
            return RestResult.error("9999","查询账号失败....");
        }
        sysUser.setDeptId(uccUserRequest.getQueryDeptId());
        PageResult<SysUser> sysUserPageResult = sysUserService.queryPage(sysUser, new Page() {{
            setStart(uccUserRequest.getStart());
            setLimit(uccUserRequest.getLimit());
        }});
        return RestResult.success(sysUserPageResult);
    }

    @ApiOperation("账号启用停用")
    @PostMapping("/updateUccUserStatus")
    public RestResult<Boolean> updateUccUserStatus(@RequestBody UpdateUccUserStatusRequest updateUccUserStatusRequest){
        return sysUserService.updateUccUserStatus(updateUccUserStatusRequest);
    }




}
